package com.caishi.lkx.course.api;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.ienum.ClientType;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.course.model.LiveModel;
import com.caishi.lkx.course.model.VideoChapterModel;
import com.caishi.lkx.course.model.VideoHandoutModel;
import com.caishi.lkx.course.service.ILiveService;
import com.caishi.lkx.course.service.IVideoChapterService;
import com.caishi.lkx.course.service.IVideoHandoutService;
import com.caishi.lkx.exam.service.ICategoryService;
import com.caishi.lkx.exam.service.IColumnService;
import com.caishi.lkx.user.model.KcLiveUserModel;
import com.caishi.lkx.user.model.MaterialInfoModel;
import com.zzw.common.entity.impl.BaseAbsEntity;
import com.zzw.common.exception.BizException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;


/**
 * @author lkx
 * &#064;date  2024/5/27
 * &#064;
 */
@Slf4j
@Tag(name = "直播相关接口")
@RestController
@RequestMapping("/kc/course/live")
public class LiveApi extends AdminBaseApi<ILiveService, LiveModel, String> {


    @Resource
    private ILiveService liveService;

    @Resource
    private ICategoryService categoryService;

    @Resource
    private IColumnService columnService;
    @Resource
    private IVideoChapterService chapterService;
    @Resource
    private IVideoHandoutService videoHandoutService;


    @Override
    public ILiveService loadService() {
        return liveService;
    }

    @Override
    protected List<LiveModel> listCover(List<LiveModel> result, JSONObject otherParam) {
        List<Long> ids = result.stream().map(LiveModel::getCategoryId).toList();
        if (!ids.isEmpty()) {
            categoryService.selectList(categoryService.wrappers().in(ids.size() > 1, BaseAbsEntity::getId, ids)).forEach(c -> {
                result.forEach(r -> {
                    if (r.getCategoryId().equals(c.getId()))
                        r.setCategoryName(c.getName());
                });
            });
        }
        return super.listCover(result, otherParam);
    }

    @GetMapping("/live-by-columnId")
    @Operation(summary = "根据栏目拉取直播列表")
    @Parameters({
            @Parameter(name = "columnId", description = "栏目id", required = true),
            @Parameter(name = "page", description = "分页模型"),
    })
    @Roles
    public IPage<LiveModel> getPaperForColumn(@ModelAttribute Page<LiveModel> page,
                                              @RequestParam(required = true) String columnId,
                                              @RequestParam Long categoryId
    ) throws BizException {

        Map<String, Object> param = MapUtil.<String, Object>builder()
                .put("columnId", columnId).build();
        var userId = userContext.currentUserId();

        MaterialInfoModel m = new MaterialInfoModel();

        IPage<LiveModel> resultPage = this.loadService().liveByColumnIdPage(page, param);
        if (StrUtil.isNotBlank(userId)) {
            boolean freeFlag = columnService.currentHaveAuth(null, null, userId, categoryId, columnId, ClientType.zyksApp);
            resultPage.getRecords().forEach(materialInfoModel -> {
                if (!materialInfoModel.getFreeFlag())
                    materialInfoModel.setFreeFlag(freeFlag);

            });
        }


        return resultPage;
    }

    public enum VideoFreeFlag {
        freeFlag(0, "免费"),
        payFlag(1, "收费"),
        all(2, "全部");
        private final Integer code;
        private final String name;

        VideoFreeFlag(Integer code, String name) {
            this.code = code;
            this.name = name;
        }

        public Integer getCode() {
            return code;
        }

        public String getName() {
            return name;
        }
    }

    //    获取最近的三个直播,如果选择了科目，则根据该科目栏目获取,已结束的不可预约
    @GetMapping("/videoList")
    @Roles
    public IPage<LiveModel> videoList(

            @RequestParam(required = false) String columnId,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "3") Integer pageSize,
            @RequestParam(required = false, defaultValue = "all") VideoFreeFlag isFree,
            @RequestParam(required = false) List<String> columnIds,
            @RequestParam(required = false, defaultValue = "true") boolean noLogin
    ) throws BizException {
        Page<LiveModel> page = new Page<>(pageNum, pageSize);
        if (categoryId != null && columnId != null) {
            return getPaperForColumn(page, columnId, categoryId);
        }

//        ex_column_config_re的config_id即live_id
//        怎么知道属于哪个栏目呢?先获取所有栏目id，栏目id是否在or_user_assets_data表里，如果存在，则获取该栏目下的直播列表
//        userAssetsDataService.userHaveAsset(userId, AssetsType.column, columnId)
//        IPage<LiveModel> resultPage = this.loadService().list(page,categoryId);


        var userId = userContext.currentUserId();
//        直播id与章节id(config_id)是一样的吗
        Map<String, Object> param = MapUtil.<String, Object>builder()
                .put("columnIds", columnIds)
                .put("isFree", isFree.getCode())
                .put("userId", userId)
                .build();
        MaterialInfoModel m = new MaterialInfoModel();

        IPage<LiveModel> resultPage;
        if (noLogin) {
            resultPage = this.loadService().list(page, categoryId);
        } else {
            if (StrUtil.isNotBlank(userId)) {
                resultPage = this.loadService().list1(page, param);

            } else {
                throw new BizException("请先登录");
            }
        }

        return resultPage;
    }

    @GetMapping("/getDetail")
    public LiveModel getDetail(@RequestParam String id) throws BizException {
        LiveModel liveModel = this.loadService().getDetail(id);
        return liveModel;
    }

    @PostMapping("/appoint")
    public boolean appoint(@RequestBody KcLiveUserModel liveModel) throws BizException {
        if (userContext.currentUserId() == null) {
            throw new BizException("请先登录");
        }
        if (liveModel.getLiveId() != null) {
//            查看是否已经预约
            KcLiveUserModel live = this.loadService().getLiveUser(userContext.currentUserId(), liveModel.getLiveId());
            if (live == null) {
//                已结束的直播不可预约
                LiveModel liveById = this.loadService().getById(liveModel.getLiveId());
                if (liveById == null) {
                    throw new BizException("没有该直播");
                }
                String str = liveById.getLiveDate() + " " + liveById.getEndTime();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime endTime = LocalDateTime.parse(str, formatter);
                if (endTime.isBefore(LocalDateTime.now())) {
                    throw new BizException("直播已结束");
                }
//                插入预约数据
                this.loadService().insertLiveUser(userContext.currentUserId(), liveModel.getLiveId());
                return true;
            } else {
                throw new BizException("请勿重复预约");
            }
        }
        throw new BizException("请选择直播");
    }

    @GetMapping("/haveAppoint")
    public boolean haveAppoint(@RequestParam String liveId) throws BizException {
        if (userContext.currentUserId() == null) {
            throw new BizException("请先登录");
        }
        if (liveId != null) {
//            查看是否已经预约
            KcLiveUserModel liveUser = this.loadService().getLiveUser(userContext.currentUserId(), liveId);
            if (liveUser != null) {
                return true;
            } else {
                return false;
            }
        }
        throw new BizException("请选择直播");
    }

    /**
     * 假使直播id对应config_id（即章节id）
     * 获取视频讲义，即章节对应的pdf
     */

    @GetMapping("/getResource")
    @Roles
    public List<VideoHandoutModel> getResource(@RequestParam(required = false) String chapterId, @RequestParam(required = false) String columnId) {
        QueryWrapper<VideoChapterModel> wrapper = new QueryWrapper<>();
        wrapper.eq("id", chapterId);
        VideoChapterModel videoChapterModel = chapterService.selectOne(wrapper);
        List<String> videoIds = videoChapterModel.getVideoIds();
        List<VideoHandoutModel> videoHandoutModels = videoHandoutService.selectList(new LambdaQueryWrapper<VideoHandoutModel>().in(VideoHandoutModel::getVideoId, videoIds).orderByDesc(VideoHandoutModel::getDownloadCount));
        return videoHandoutModels;
    }


}
